package com.cf.exception;

import com.cf.domain.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    public Object handleLzqException(HttpServletRequest request, HttpServletResponse response, Exception e){
        //判断请求来源，是页面还是数据
        boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
        log.error(e.getMessage(), e);

        if(isAjax){
            //如果是数据
            if(e instanceof MyException){
                MyException myException = (MyException) e;
                return new ResponseEntity<>(ResponseResult.fail(myException.getMessage()), HttpStatus.OK);
            }
            return new ResponseEntity<>(ResponseResult.fail("500", "服务器端异常"), HttpStatus.OK);
        }else{
            // 如果是页面请求，返回ModelAndView到错误页面
            ModelAndView modelAndView = new ModelAndView("error");
            modelAndView.addObject("error", e.getMessage());
            return modelAndView;
        }
    }

}
